package net.cyndeline.xml

import scala.xml.Elem
import com.escalatesoft.subcut.inject.BindingModule
import com.escalatesoft.subcut.inject.Injectable
import scala.util.Random
import scala.xml.Node

class AmountParser(implicit val bindingModule: BindingModule) extends Amount with Injectable {
  
  override def key = "value"
  
  override def parse(value: Node): Int = {
    val fixedAmount = value \ "fixed"
    
    if (!fixedAmount.isEmpty) {
      return fixedAmount.text.toInt
    }
    
    val rangeStart = value \ "from"
    val rangeStop = value \ "to"
    
    if (!rangeStart.isEmpty && !rangeStop.isEmpty) {
      val result = injectOptional[Random] getOrElse new Random()
      val start = rangeStart.text.toInt
      val stop = rangeStop.text.toInt
      val ret = result.nextInt(stop - start + 1) + start
      return ret
    }
    
    throw new Error("Value tag missing a valid amount.")
  }
}